import React, {
  useState,
  useEffect,
  useRef,
  useContext,
  createContext
} from 'react'
import { Table, Button, Modal, Form, Input, message } from 'antd'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { getCategoriesApi, delCategoriesApi, updateCategorieApi } from '@/api/categories'

export default function NewsCategory() {
  // 页面数据源
  const [categoryList, setCategoryList] = useState([])
  // 跨组件传递的内容组件
  const EditableContext = createContext(null)

  useEffect(() => {
    getCategoryList()
  }, [])

  //获取分类列表
  const getCategoryList = async () => {
    const response = await getCategoriesApi()
    const categoryList = response
    setCategoryList(categoryList)
  }

  // 定义点击删除新闻分类按钮的回调
  const confirmMethod = item => {
    Modal.confirm({
      title: '系统提示',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined/>,
      content: `删除分类名称:${item.title},删除后无法恢复,你确定要删除吗?`,
      onOk() {
        delCategoriesApi(item.id).then(() => {
          message.success('删除成功')
          getCategoryList()
        })
      }
    })
  }

  // 保存修改
  const handleSave = record => {
    updateCategorieApi(record.id, {
      title: record.title,
      value: record.title
    }).then(() => {
      message.success('修改成功')
      getCategoryList()
    })
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: id => {
        return <b>{id}</b>
      }
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      // 设置单元格属性，传入的是一个函数
      onCell: record => ({
        record,
        editable: true,
        dataIndex: 'title',
        title: '栏目名称',
        handleSave
      }),
      width: 500
    },
    {
      title: '操作',
      render: item => {
        return (
          <Button
            danger
            icon={<DeleteOutlined/>}
            onClick={() => confirmMethod(item)}
            shape="circle"
          />
        )
      }
    }
  ]

  const EditableRow = ({ ...props }) => {
    const [form] = Form.useForm()
    return (
      <Form component={false} form={form}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    )
  }

  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false)
    const inputRef = useRef(null)
    const form = useContext(EditableContext)
    useEffect(() => {
      if (editing) {
        inputRef.current.focus()
      }
    }, [editing])

    const toggleEdit = () => {
      setEditing(!editing)
      form.setFieldsValue({
        [dataIndex]: record[dataIndex]
      })
    }

    const save = async () => {
      try {
        const values = await form.validateFields()
        toggleEdit()
        handleSave({
          ...record,
          ...values
        })
      } catch (errInfo) {
        console.log('Save failed:', errInfo)
      }
    }
    let childNode = children
    if (editable) {
      childNode = editing ? (
        <Form.Item
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`
            }
          ]}
          style={{
            margin: 0
          }}
        >
          <Input onBlur={save} onPressEnter={save} ref={inputRef}/>
        </Form.Item>
          ) : (
            <div
              className="editable-cell-value-wrap"
              onClick={toggleEdit}
              style={{
                paddingRight: 24,
                cursor: 'pointer'
              }}
            >
              {children}
            </div>
          )
    }
    return <td {...restProps}>{childNode}</td>
  }

  return (
    <Table
      columns={columns}
      components={{
        body: {
          row: EditableRow,
          cell: EditableCell
        }
      }}
      dataSource={categoryList}
      pagination={{ pageSize: 5 }}
      rowKey={item => item.id}
    />
  )
}